package com.ruoyi.common.utils.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;

public class SQLServerUtil {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:sqlserver://172.30.30.30:1433;databaseName=HC2024;encrypt=true;trustServerCertificate=true;sslProtocol=TLSv1.2";
    private static final String USER = "sa";
    private static final String PASSWORD = "Nbhcit-2020";

    /**
     * 获取数据库连接
     *
     * @return Connection 对象
     * @throws SQLException 如果连接失败
     */
    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(DB_URL, USER, PASSWORD);
    }

    /**
     * 读取表 a 的内容
     */
    public static void readTableA() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            System.setProperty("jdk.tls.client.protocols", "TLSv1.0");
            System.setProperty("https.protocols", "TLSv1.0");
            // 获取数据库连接
            conn = getConnection();
            System.out.println("成功连接到数据库！");

            // 创建 Statement 对象
            stmt = conn.createStatement();

            // 执行查询语句
            String sql = "SELECT * FROM btype";
            rs = stmt.executeQuery(sql);

            // 遍历结果集
            while (rs.next()) {
                // 假设表 a 有两列：id 和 name
                int id = rs.getInt("id");
                String name = rs.getString("name");

                // 输出数据
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        // 调用方法读取表 a 的内容
        readTableA();
    }
}